Use Effect

One of the main benefits of lifecycle methods in class components is that they allow for us to program many side effects. UseEffect simply lets us apply any side effect that we'd like to our functional components. A typical usage of side effects could be making network requests to another service, logging analytics, or updating DOM elements manually.

When using the useEffect hook, we're telling react that we want to do something immediately after rendering, so once we do render (or re-render) a component, react will call the function(s) within our useEffect and invoke it!

 

Implementing useEffect:

If we take our network calls from theAPI calls module and convert them to using hooks, we get:

Take note of the useEffect on line 26. Because useEffect gets kicked off after every render, we want to write some logic to make sure that we don't make the network calls, update our state, re-render, call useEffect, make another network call, update our state, re-render, call useEffect, make another network call, and so on infinitely. With a quick check of our state variable, we can quickly make sure we only call our network calls once.

 

Separation of Concerns

While you could do everything in one single useEffect, to keep your code clean, you can use as many useEffects as you like! Suppose that you'd want to set the title of the page based upon the number of elements that were filtered by the handleSearch function. We could use the same useEffect, but making a network call has almost nothing to do with setting our page's title, so we should use a different useEffect:

 

Separation of concerns is not necessary, but it does make finding and updating code significantly easier.